package com.blog.subject.application.interceptor;

import com.blog.subject.common.context.LoginContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * 实现了 HandlerInterceptor 接口，表明这是一个Spring MVC的拦截器。
 * @author: Blog
 * @date: 2023/11/26
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 在请求处理前被调用。
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String loginId = request.getHeader("loginId");    //通过 HttpServletRequest 获取请求头中的 loginId，表示用户的登录标识。
        if (StringUtils.isNotBlank(loginId)) {
            LoginContextHolder.set("loginId", loginId);   //LoginContextHolder 负责管理登录上下文信息
        }
        return true;
    }

    /**
     *在整个请求完成后被调用
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        LoginContextHolder.remove();  //移除当前线程中的登录上下文信息
    }

}
